//
//  RateDetailsController.m
//  NiuBanJin
//
//  Created by Billy on 15/11/20.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "RateDetailsController.h"
#import "RateDetailCell.h"
#import "WebViewController.h"
@interface RateDetailsController () <UITableViewDataSource,UITableViewDelegate,UITabBarDelegate>

@property (nonatomic, strong) UIView *view_header; //牛头像红背景
@property (nonatomic, strong) UIView *view_context; //文字解释

@property (nonatomic, strong) UITableView *tableView; //显示利率内容
@property (nonatomic, strong) NSMutableArray *mutableArray_allRate; //加息券数据源
@property (nonatomic, strong) NSArray *array_allText;// 文案内容
@end

@implementation RateDetailsController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self pageSettingsAndSubviewsCreation];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self getDataFromServer];
}

#pragma mark - SubviewsCreationAndPageSettings

- (void) pageSettingsAndSubviewsCreation {
    
    [self.navigationItem setTitle:@"加息券加息状态"];
    [self.view setBackgroundColor:BASECOLOR];
    
    [self.view addSubview:self.view_header];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.view_context];
}

#pragma mark - TableView datasource && delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.mutableArray_allRate count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView setRowHeight:MULTIPLYHEIGHT(180.0/2)];
    
    static NSString *identifer = @"cellDetailRate" ;
    
    RateDetailCell *cell = (RateDetailCell *)[tableView dequeueReusableCellWithIdentifier:identifer];
    
    if (!cell) {
        
        cell = [[RateDetailCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifer];
    }
    
    if ([self.mutableArray_allRate count] > 0) {
        
        cell.rateDetail =  self.mutableArray_allRate[indexPath.row];
    }
    
    return  cell;
}

#pragma mark - data preparation

- (void) getDataFromServer {
    
    NSDictionary *dic_params = @{@"userId":GETCURRENTUSERINOBYPRAMETERES(user_userId),@"token":GETCURRENTUSERINOBYPRAMETERES(user_userToken)};
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [[NetworkUtil sharedNetworkUtil] zzjrRateDetailsByParmeteres:dic_params transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if (!error) {
            
            [self.mutableArray_allRate removeAllObjects]; //clear history data
            
            NSDictionary *dic_result = parsedData;
            
            if ([dic_result[@"status"] integerValue] == 0) {
                
                [self  parsedRateDetailsByDic:dic_result[@"result"]];
                
            }else {
                
                [UsefulUtil showAlertView:dic_result[@"msg"]];
            }
            
        }else {
            
            [UsefulUtil showAlertView:error.description];
        }
    }];
}

// 因为这个数据量小就在C里解析好了

- (void) parsedRateDetailsByDic:(NSDictionary *) dic {
    
    for (NSDictionary *dic_element in dic[@"ticketRateList"]) {
        
        RateDetail *tmp = [[RateDetail alloc] initWithAttributes:dic_element];
        [self.mutableArray_allRate addObject:tmp];
    }
    
    if ([self.mutableArray_allRate count] >0) {
        
        [self.tableView reloadData];
    }
}


- (UIView *)view_header {
    
    if (!_view_header) {
        
        _view_header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(220.0/2))];
        [_view_header.layer setContents:(__bridge id)([UIImage imageNamed:@"viewTop"].CGImage)];
        
        // 牛像
        CALayer *layer_cow = [self layerCreationWithFrame:CGRectMake(MULTIPLYWIDTH(26.0/2), MULTIPLYHEIGHT(30.0/2),MULTIPLYWIDTH(157.0/2), MULTIPLYHEIGHT(157.0/2)) andContents:(__bridge id)[UIImage imageNamed:@"cow"].CGImage];
        [_view_header.layer addSublayer:layer_cow];
        
        // 当前年化收益
        
        UILabel *label_ratePrompt = [UsefulUtil labelCreationWithFrame:CGRectMake(CGRectGetMaxX(layer_cow.frame) + MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(41.0/2), MULTIPLYWIDTH(220.0/2), MULTIPLYHEIGHT(34.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont boldSystemFontOfSize:15.0] text:@"当前年化收益:"];

        [_view_header addSubview:label_ratePrompt];
        
        // 真正的收益显示:
        
        UILabel *label_rateShown = [UsefulUtil labelCreationWithFrame:CGRectMake(CGRectGetMaxX(label_ratePrompt.frame) + MULTIPLYWIDTH(30.0/2), MULTIPLYHEIGHT(17.0/2), SCREEN_WIDTH - CGRectGetMaxX(label_ratePrompt.frame)-  MULTIPLYWIDTH(30.0/2), MULTIPLYHEIGHT(70.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont boldSystemFontOfSize:40.0] text:@"8%"];
        
        if (self.dic_rateInfo) {
            
            NSString *str_original = self.dic_rateInfo[@"rate"];
            NSString *str_adding = self.dic_rateInfo[@"addingRate"];
            
            NSString *str_rate = [NSString stringWithFormat:@"%@%%+%@%%",str_original,str_adding];
            
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str_rate];
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:(iPhone4?30:40)] range:NSMakeRange(0, str_original.length)];//8
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(str_original.length , 2)]; //%+
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:(iPhone4?30:40)] range:NSMakeRange(str_original.length+2 , str_adding.length)]; //1
            
            [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(str_rate.length - 1, 1)]; //%

            [label_rateShown setAttributedText:attrStr];
        }
    
        [label_rateShown setAdjustsFontSizeToFitWidth:NO];
        [label_rateShown setTag:20];
        
        [_view_header addSubview:label_rateShown];
        
        // 有效期
        
        NSString *content = nil;
        
        if (self.dic_rateInfo[@"expiredDate"]) {
            
            content = [NSString stringWithFormat:@"当前年化收益持续时间至: %@",self.dic_rateInfo[@"expiredDate"]];
        }else{
            
            content = @"";
        }
        
        UILabel *label_expiredDate = [UsefulUtil labelCreationWithFrame:CGRectMake(label_ratePrompt.frame.origin.x, CGRectGetMaxY(label_ratePrompt.frame) +MULTIPLYHEIGHT(37.0/4) , MULTIPLYWIDTH(400.0/2), MULTIPLYHEIGHT(44.0/2)) textColor:[UIColor whiteColor] fontName:[UIFont boldSystemFontOfSize:11.0] text:content];
        
        [_view_header addSubview:label_expiredDate];
        
        [label_expiredDate setTag:21];
        
        //获取方法和使用规则
        
        UIButton *button_usageGuide = [[UIButton alloc] initWithFrame:CGRectMake(label_expiredDate.frame.origin.x - 2.0, CGRectGetMaxY(label_expiredDate.frame) + MULTIPLYHEIGHT(23.0/2), MULTIPLYWIDTH(222.0/2), MULTIPLYHEIGHT(40.0/2))];
        
        [button_usageGuide addTarget:self action:@selector(ticketUsageGuideButtonHandle:) forControlEvents:UIControlEventTouchUpInside];
        
        [button_usageGuide setBackgroundColor:[UIColor whiteColor]];
        [button_usageGuide setTitleColor:[UsefulUtil colorWithHexString:@"#fb4747"] forState:UIControlStateNormal];
        [button_usageGuide.titleLabel setFont:[UIFont systemFontOfSize:11.0]];
        [button_usageGuide.layer setCornerRadius:MULTIPLYHEIGHT(20.0/2)];
        [button_usageGuide setTitle:@"获取方法和使用规则" forState:UIControlStateNormal];
        [button_usageGuide.titleLabel setAdjustsFontSizeToFitWidth:YES];
        [_view_header addSubview:button_usageGuide];
        
    }
    
    return _view_header;
}

- (CALayer *) layerCreationWithFrame:(CGRect ) frame andContents:(id) content {
    
    CALayer *layer_tmp = [CALayer layer];
    [layer_tmp setFrame:frame];
    [layer_tmp setContents:content];
    
    return layer_tmp;
}

#pragma mark - button event handling

// 兑换规则
- (void) ticketUsageGuideButtonHandle: (UIButton *) button {
    
    WebViewController *webVC = [[WebViewController alloc]init];
    webVC.index = 9;
    [self.navigationController pushViewController:webVC animated:YES];
//    [UsefulUtil showAlertView:@"这儿会链接一个H5网页来显示"];
//    NSLog(@"动态h5页面显示");
    
}

#pragma mark - setter methods

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_header.frame), SCREEN_WIDTH, MULTIPLYHEIGHT(620.0/2) ) style:UITableViewStylePlain];
        
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setBackgroundColor:BASECOLOR];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        [_tableView setAllowsSelection:NO];
    }
    
    return  _tableView;
}

- (UIView *)view_context {
    
    if (!_view_context) {
        
        _view_context = [UsefulUtil viewCreationWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame) + MULTIPLYHEIGHT(41.0/2), SCREEN_WIDTH, MULTIPLYHEIGHT(190.0/2)) backgroundColor:BASECOLOR backGroundImage:nil];
        
        // 温馨提示
        UIImageView *imageView = [UsefulUtil imageViewCreationWithFrame:CGRectMake(MULTIPLYWIDTH(30.0/2), 0, MULTIPLYWIDTH(23.0/2), MULTIPLYWIDTH(20.0/2)) image:[UIImage imageNamed:@"heart"]];
        
        [_view_context addSubview:imageView];
        
        UILabel *label_promptMiddle = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame), imageView.frame.origin.y - MULTIPLYHEIGHT(4.0/2), MULTIPLYWIDTH(100.0/2), MULTIPLYHEIGHT(30.0/2))];
        
        [label_promptMiddle setTextColor:[UsefulUtil colorWithHexString:@"#989898"]];
        [label_promptMiddle setText:@"温馨提示"];
        [label_promptMiddle setFont:[UIFont systemFontOfSize:11.0]];
        
        [_view_context addSubview:label_promptMiddle];
        
        for (int i = 0; i < 5; i++) {
            
            UILabel *label_tmp = [[UILabel alloc] initWithFrame:CGRectMake(label_promptMiddle.frame.origin.x,CGRectGetMaxY(label_promptMiddle.frame) + MULTIPLYHEIGHT(35.0/2)*i +MULTIPLYHEIGHT(15.0/2) , SCREEN_WIDTH - MULTIPLYWIDTH(60.0/2), MULTIPLYHEIGHT(20.0/2))];
            
            [label_tmp setTextColor:[UsefulUtil colorWithHexString:@"#989898"]];
            [label_tmp setFont:[UIFont systemFontOfSize:12.0]];
            [label_tmp setText:self.array_allText[i]];
            
            NSLog(@"label_tmp:%@",NSStringFromCGRect(label_tmp.frame));
            [_view_context addSubview:label_tmp];
        }
        
    }
    
    return _view_context;
}

- (NSMutableArray *)mutableArray_allRate {
    
    if (!_mutableArray_allRate) {
     
        _mutableArray_allRate = [NSMutableArray array];
    }
    
    return _mutableArray_allRate;
}

- (NSArray *)array_allText {
    
    if (!_array_allText) {
        
        _array_allText = @[@"1.同种颜色加息券使用有效加息时间叠加;",@"2.不同颜色加息券使用利率(年化收益)叠加;"
                           ,@"3. 当前年化收益以最高收益为准;",@"4.最高收益持续时间以加息券最少时间为准;",
                           @"5.相关规则详见加息券使用规则。"];
    }
    
    return _array_allText;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


@end
